package com.hefan.api.service.pay;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.PaymentTypeEnum;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;

import com.hefan.common.pay.wechat.Signature;
import com.hefan.common.pay.wechat.Util;
import com.hefan.common.pay.wechat.XMLParser;
import com.hefan.pay.bean.ThridPartyNotifyVo;
import com.hefan.pay.bean.TradeLog;
import com.hefan.pay.itf.PayOpreateHandlerService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Map;

/**
 * Created by lxw on 2016/10/12.
 */
@Component
public class PayNotifyOprateLocalService {
    private Logger logger = LoggerFactory.getLogger(PayNotifyOprateLocalService.class);

    @Reference
    private PayOpreateHandlerService payOpreateHandlerService;

    @Resource
    private PayLocalService payLocalService;

    /**
     * 微信回调处理
     * @param reqInputStream
     * @return
     */
    public ResultBean wechatNotifyOprate(InputStream reqInputStream) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        try {
            String xmlStr = Util.inputStreamToString(reqInputStream);
            logger.info("wechatNotifyOprate-----------xmlStr:"+xmlStr);
            if(StringUtils.isBlank(xmlStr)) {
                res = new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.PayNotifyParamEmpty.getMsg(),null);
            }
            //组装回调请求处理入参Vo对象
            ThridPartyNotifyVo thridPartyNotifyVo = new ThridPartyNotifyVo();
            thridPartyNotifyVo.setWechatRequstParamStr(xmlStr);
            thridPartyNotifyVo.setPaymentType(PaymentTypeEnum.ANDROID_WECHAT_PAY.getPaymentType());
            //第三方支付回调通知处理
            res = payOpreateHandlerService.thridPartyPayNotfiyOprater(thridPartyNotifyVo);
            if(res.getData() != null) {
                //进行更新充值状态|如果成功增加用户饭票数
                payLocalService.payNotifySuccessHandler((TradeLog)res.getData());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            res = new ResultBean(ResultCode.UNSUCCESS.get_code(),e.getMessage(),null);
        }
        return res;
    }

    /**
     * 支付宝app支付回调处理
     * @param request
     * @return
     */
    public ResultBean alipayAppNotifyOprate(HttpServletRequest request) {
        logger.info("alipayAppNotifyOprate ------------------- begin");
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map requestParamsMap = request.getParameterMap();
            if(!CollectionUtils.isEmpty(requestParamsMap)) {
                //支付宝支付回调通知组装回调处理vo
                ThridPartyNotifyVo thridPartyNotifyVo = alipayThridPartyNotifyVoCreater(requestParamsMap, request, PaymentTypeEnum.ANDROID_ALIPAY_PAY.getPaymentType());
                //第三方支付回调通知处理
                res = payOpreateHandlerService.thridPartyPayNotfiyOprater(thridPartyNotifyVo);
                if(res.getData() != null) {
                    //进行更新充值状态|如果成功增加用户饭票数
                    payLocalService.payNotifySuccessHandler((TradeLog)res.getData());
                }
            } else {
                res = new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.PayNotifyParamEmpty.getMsg(),null);
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            res = new ResultBean(ResultCode.UNSUCCESS.get_code(),e.getMessage(),null);
        }
        logger.info("alipayAppNotifyOprate ------------------- end"+ JSON.toJSONString(res));
        return res;
    }

    /**
     * 支付宝及时到账回调通知处理
     * @param request
     * @return
     */
    public ResultBean alipaySacnCodeNotifyOprate(HttpServletRequest request) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map requestParamsMap = request.getParameterMap();
            if(!CollectionUtils.isEmpty(requestParamsMap)) {
                //支付宝支付回调通知组装回调处理vo
                ThridPartyNotifyVo thridPartyNotifyVo = alipayThridPartyNotifyVoCreater(requestParamsMap, request, PaymentTypeEnum.PC_ALIPAY_PAY.getPaymentType());
                //第三方支付回调通知处理
                res = payOpreateHandlerService.thridPartyPayNotfiyOprater(thridPartyNotifyVo);
                if(res.getData() != null) {
                    //进行更新充值状态|如果成功增加用户饭票数
                    payLocalService.payNotifySuccessHandler((TradeLog)res.getData());
                }
            } else {
                res = new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.PayNotifyParamEmpty.getMsg(),null);
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            res = new ResultBean(ResultCode.UNSUCCESS.get_code(),e.getMessage(),null);
        }
        return res;
    }

    /**
     * 支付宝手机网站支付
     * @param request
     * @return
     */
    public ResultBean alipayWapNotifyOprate(HttpServletRequest request) {
        logger.info("PayNotifyOprateLocalService----alipayWapNotifyOprate--- begin");
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map requestParamsMap = request.getParameterMap();
            if(!CollectionUtils.isEmpty(requestParamsMap)) {
                //支付宝支付回调通知组装回调处理vo
                ThridPartyNotifyVo thridPartyNotifyVo = alipayThridPartyNotifyVoCreater(requestParamsMap, request, PaymentTypeEnum.ALIPAY_HTML5_PAY.getPaymentType());
                logger.info("PayNotifyOprateLocalService----alipayWapNotifyOprate--- thridPartyNotifyVo:"+JSON.toJSONString(thridPartyNotifyVo));
                //第三方支付回调通知处理
                res = payOpreateHandlerService.thridPartyPayNotfiyOprater(thridPartyNotifyVo);
                logger.info("PayNotifyOprateLocalService----alipayWapNotifyOprate--- 处理完成返回:"+JSON.toJSONString(res));
                if(res.getData() != null) {
                    //进行更新充值状态|如果成功增加用户饭票数
                    payLocalService.payNotifySuccessHandler((TradeLog)res.getData());
                }
            } else {
                res = new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.PayNotifyParamEmpty.getMsg(),null);
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            res = new ResultBean(ResultCode.UNSUCCESS.get_code(),e.getMessage(),null);
        }
        logger.info("PayNotifyOprateLocalService----alipayWapNotifyOprate---end---res:"+JSON.toJSONString(res));
        return res;
    }

    /**
     * 苹果内购检查
     * @param orderId
     * @param appleReceipt
     * @param transactionId
     * @return
     */
    public ResultBean appleAppStoreCheckOprate(String orderId, String appleReceipt, String transactionId) {
        ResultBean res = new ResultBean(ResultCode.SUCCESS,null);
        ThridPartyNotifyVo thridPartyNotifyVo = new ThridPartyNotifyVo();
        thridPartyNotifyVo.setOrderId(orderId);
        thridPartyNotifyVo.setAppleReceipt(appleReceipt);
        thridPartyNotifyVo.setPaymentType(PaymentTypeEnum.IOS_APPLE_PAY.getPaymentType());
        thridPartyNotifyVo.setTransactionId(transactionId);
        //apple app store 支付验证
        res = payOpreateHandlerService.thridPartyPayNotfiyOprater(thridPartyNotifyVo);
        if(res.getData() != null) {
            //进行更新充值状态|如果成功增加用户饭票数
            payLocalService.payNotifySuccessHandler((TradeLog)res.getData());
        }
        return res;
    }

    /**
     * 支付宝支付回调通知组装回调处理vo
     * @param reqeustParamsMap
     * @param request
     * @param paymentType
     * @return
     * @throws Exception
     */
    private ThridPartyNotifyVo alipayThridPartyNotifyVoCreater(Map reqeustParamsMap,
                                                               HttpServletRequest request, int paymentType) throws Exception {
        //商户订单号
        String orderId = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String thirdPartyTradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //交易状态
        String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        //支付金额
        String totalAmount  = "0";
        if(paymentType == PaymentTypeEnum.ANDROID_ALIPAY_PAY.getPaymentType() || paymentType == PaymentTypeEnum.ALIPAY_HTML5_PAY.getPaymentType()) {//app支付|手机网站支付
            totalAmount  = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
        } else if (paymentType == PaymentTypeEnum.PC_ALIPAY_PAY.getPaymentType()) { //及时到账
            totalAmount  = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
        }
        //支付宝卖家sellerId
        String sellerId  = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
        //组装回调请求处理入参对象
        ThridPartyNotifyVo thridPartyNotifyVo = new ThridPartyNotifyVo();
        thridPartyNotifyVo.setAliPayRequestParamsMap(reqeustParamsMap);
        thridPartyNotifyVo.setOrderId(orderId);
        thridPartyNotifyVo.setThirdPartyTradeNo(thirdPartyTradeNo);
        thridPartyNotifyVo.setAlipayTradeStatus(tradeStatus);
        thridPartyNotifyVo.setTotalAmount(totalAmount);
        thridPartyNotifyVo.setAlipaySellerId(sellerId);
        thridPartyNotifyVo.setPaymentType(paymentType);
        return thridPartyNotifyVo;
    }

}
